package ar.edu.caece.pl.asem.codegenerator;

import java.util.LinkedHashMap;
import java.util.Map;

import ar.edu.caece.pl.asem.model.impl.Ambiente;
import ar.edu.caece.pl.asem.model.impl.SymbolTable;
import ar.edu.caece.pl.asem.model.impl.treeelements.AbstractElement;
import ar.edu.caece.pl.asem.model.impl.treeelements.Arreglo;
import ar.edu.caece.pl.asem.model.impl.treeelements.MetodoGenerico;
import ar.edu.caece.pl.asem.model.impl.treeelements.SimboloGenerico;
import ar.edu.caece.pl.asin.manager.impl.ErrorManager;

public class Assembler {
	public static final String TAB = "\t";
	public static final String ENTER = "\n";
	
	
	public String start() {
		StringBuffer sb = new StringBuffer();
		if(ErrorManager.debugEnabled) {			
			sb.append("; ASM-Start - Init" + ENTER);
		}
		sb.append("ORG 100h" + ENTER);
		sb.append("JMP main" + ENTER);
		if(ErrorManager.debugEnabled) {			
			sb.append("; ASM-Start - Finish" + ENTER);
		}
		return sb.toString();
	}

	public String generateGlobalMemory() {
		StringBuffer sb = new StringBuffer();
		if(ErrorManager.debugEnabled) {
			sb.append("; GlobalMemory - Init" + ENTER);
		}
		Ambiente global = SymbolTable.getInstance().getAmbiente(SymbolTable.GLOBAL);
		Map<String, AbstractElement> symbolNodes = new LinkedHashMap<String, AbstractElement>();
		symbolNodes.putAll(global.getArreglos());
		symbolNodes.putAll(global.getConstantes());
		symbolNodes.putAll(global.getVariables());
		
		for (AbstractElement symbol : symbolNodes.values()) {
			if (symbol instanceof MetodoGenerico) {
				String key = "ret_null_" + symbol.getName();
				sb.append(key + " dw " + ((MetodoGenerico)symbol).getReturnType() + ENTER);
			}

			sb.append(symbol.getEnvName() + "_" + symbol.getName() + " dw ");
			if (symbol instanceof Arreglo) {
				int size = ((Arreglo)symbol).getLength();
				StringBuffer def = new StringBuffer();
				for (int i = 0; i < size; i++) {
					if (i < size -1 ){
						sb.append("0, ");
					}else{
						sb.append("0" + ENTER);
					}
				}
			} 
			else {
				sb.append( ((SimboloGenerico)symbol).getValue() + ENTER);
			}
		}
		if(ErrorManager.debugEnabled) {
			sb.append("; GlobalMemory - Finish" + ENTER);
		}
		return sb.toString();
	}
	
}
